package com.veromca.sendserver.service;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.veromca.mqclient.TransactionMqRemoteClient;
import com.veromca.mqclient.dto.TransactionMessage;
import com.veromca.common.biz.BaseBiz;
import com.veromca.sendserver.mapper.TransactionOrderMapper;
import com.veromca.sendserver.po.TransactionOrderPO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @Description:
 * @Author: liusongqing
 * @CreateDate: 2019/12/01
 * @UpdateUser:
 * @UpdateDate:
 * @Copyright:
 * @UpdateRemark:
 * @Version: 0.2
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TransactionOrderServiceImpl extends BaseBiz<TransactionOrderMapper, TransactionOrderPO> implements ITransactionOrderService {
    @Autowired
    private TransactionOrderMapper transactionMessageMapper;
    @Autowired
    private TransactionMqRemoteClient transactionMqRemoteClient;

    /**
     * 修改订单状态
     *
     * @param message
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    public boolean updateOrderStatus(TransactionOrderPO message) {


        super.updateById(message);
        // 修改成功之后 发送消息给入库服务修改入库状态 ，最终一致
        TransactionMessage transactionMessage = new TransactionMessage();
        transactionMessage.setQueue("order_queue");
        transactionMessage.setCreateDate(new Date());
        transactionMessage.setSendSystem("order_server");
        transactionMessage.setMessage(JSON.toJSONString(message));
        transactionMessage.setDieCount(2);
        transactionMessage.setStatus(0);
        boolean result = transactionMqRemoteClient.sendMessage(transactionMessage);
        if(!result){
            throw new RuntimeException("回滚事务");
        }
        return result;
    }

}
